//
//  WBRefreshViewControl.swift
//  HMWeibo
//
//  Created by wulei on 15/12/14.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
private let WBRefreshControlOffset: CGFloat = -60
class WBRefreshViewControl: UIRefreshControl {
    // MARK: - 重写系统 endRefreshing 方法
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
    }
    
    
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
//     MARK: - 重写Frame 监听
//   override var frame: CGRect {
//    
//    didSet{
//        print(frame)
//    }
//    
//    }
    
//     MARK: - 使用KVO监听方法

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }
//        print(frame)
        if refreshing {
            refreshView.startAnimation()
            return
        }
    
    
    // MARK: - 判断临界值
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {

            refreshView.rotateFlag = true

        } else if frame.origin.y >= WBRefreshControlOffset && refreshView.rotateFlag {

            refreshView.rotateFlag = false

        }

    }
 
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        setupUI()
    }
    
    func setupUI() {
        
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        
        
        // 使用KVO监听位置变化(添加)
        // 主队列的特点: 当主线程上有任务就不调度主队列中的任务执行
        // 让当前运行循环中所有代码执行完毕后,运行循环结束前,开始监听
        // 方法触发会在下一次运行循环开始!
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }

    // 删除 KVO 监听方法
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    // 懒加载控件
    private lazy var refreshView = WBRefreshView.refreshView()
}

class WBRefreshView: UIView {
    
    
    
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    
    // 箭头返转标记属性
    var rotateFlag = false {
        didSet{
            rotateTipIconView()
        }
    }
// 旋转图标动画
   private func rotateTipIconView() {
        
        UIView.animateWithDuration(0.5) { () -> Void in
            var angle = CGFloat(M_PI)
           angle += self.rotateFlag ? -0.001 : 0.001
            
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)

        }
    }
    // 从Xib 加载视图
    class func refreshView() -> WBRefreshView {
    
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
       return nib.instantiateWithOwner(nil, options: nil)[0] as! WBRefreshView
        
    }
    
    // 播放加载动画
    private func startAnimation() {
        
        let key = "transform.rotation"
        if loadingIconView.layer.animationForKey(key) != nil {

            return
        }
        print("加载动画")
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        
        loadingIconView.layer.addAnimation(anim, forKey: key)
        
    }
    
    
    // 停止加载动画
    private func stopAnimation() {
        tipView.hidden = false
        loadingIconView.layer.removeAllAnimations()
    }
}